﻿using Framework.MVC;
using Recharge.Entry;
using Recharge.Models;
using System.Web;
using System;
using Framework.Common.Entry;
using Billing.IService.Entry;
using System.Collections.Generic;

namespace Recharge.Expand
{
    internal static class ControllerBehavior
    {

        #region Expand

        internal static void InitPageConfig(this AsyncControllerBase controller, string name)
        {
            InitConfig<KeyValueEntry<string, object>[]>(controller, name, OnPageConfig);
        }

        internal static void InitConfig<T>(this AsyncControllerBase controller, string name, Action<AsyncControllerBase,T> action)
        {
            GetConfigModel<T> model = new GetConfigModel<T>
            {
                ConfigName = name
            };
            model.Complete += (sender, e) =>
            {
                action(controller, e.Data.Value is T ? (T)e.Data.Value : default(T));
            };
            controller.InitModel(model);
        }

        internal static void InitAccount(this AsyncControllerBase controller, string name)
        {
            HttpCookie cookie = controller.Request.Cookies[name];
            controller.ViewData["Name"] = cookie == null || string.IsNullOrWhiteSpace(cookie.Value) ? null : cookie.Value;
        }

        internal static void WriteInfo(this AsyncControllerBase controller,string name,string value,string path) {
            HttpCookie errorCookie = new HttpCookie(name, value);
            errorCookie.Expires = DateTime.Now.AddMinutes(1);
            errorCookie.Path = path;
            controller.Response.AppendCookie(errorCookie);
        }
        #endregion Expand

        #region Private

        private static void OnPageConfig(AsyncControllerBase controller, KeyValueEntry<string, object>[] configs)
        {
            if (configs == null)
                return;
            foreach (var config in configs)
            {
                controller.ViewData[config.key] = config.value;
            }

        }

        #endregion Private

    }
}